using System;
using System.Drawing;
using System.Drawing.Imaging;
using Microsoft.Xna.Framework.Graphics;
using Rectangle=Microsoft.Xna.Framework.Rectangle;

namespace RebelStar.Engine.Sprites
{
    public class SpriteBase
    {
        private readonly Texture2D texture;
        private readonly int statesHoriz, statesVert;
        private readonly int border;
        private Bitmap image;

        protected SpriteBase(string assetName, int statesHoriz, int statesVert)
            : this (assetName, statesHoriz, statesVert, 0)
        {}
        protected SpriteBase(string assetName, int statesHoriz, int statesVert, int borderWidth)
        {
            this.texture = Engine.Content.ContentManager.Load<Texture2D>(assetName);
            this.statesHoriz = statesHoriz;
            this.statesVert = statesVert;
            this.border = borderWidth;

            Image im = this.Image;
        }
        public Rectangle GetState(int state)
        {
            return new Rectangle(
                border + (state%statesHoriz > 0 ? state%statesHoriz : 0)*(this.Width + border),
                border + (state/statesHoriz)*(this.Height + border),
                this.Width,
                this.Height);
        }

        public Texture2D Texture
        {
            get { return texture; }
        }
        public Image Image
        {
            get
            {
                if (image==null)
                {
                    byte[] textureData = new byte[4 * texture.Width * texture.Height];                    
                    texture.GetData(textureData);

                    image = new Bitmap(
                        texture.Width, texture.Height,
                        System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                    BitmapData bmpData = image.LockBits(
                        new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height),
                        ImageLockMode.WriteOnly,
                        PixelFormat.Format32bppArgb);

                    IntPtr safePtr = bmpData.Scan0;
                    System.Runtime.InteropServices.Marshal.Copy(textureData, 0, safePtr, textureData.Length);
                    image.UnlockBits(bmpData);
                }
                return image;
            }
        }
        public int StatesCount
        {
            get
            {
                return statesHoriz * statesVert;
            }
        }
        virtual public int Width
        {
            get
            {
                throw new NotImplementedException("");
            }
        }
        virtual public int Height
        {
            get
            {
                throw new NotImplementedException("");
            }
        }
    }
}
